package cn.itcast.n4;

import java.io.IOException;
import java.util.concurrent.locks.ReentrantReadWriteLock;

// PrintConcurrentLocks
public class Test {

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (Test.class) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1").start();

        Thread.sleep(100);
        new Thread(() -> {
            synchronized (Test.class) {

            }
        }, "t2").start();

        new Thread(() -> {
            synchronized (Test.class) {

            }
        }, "t3").start();
    }
}

class CachedData {
    Object data;
    // 是否有效
    volatile boolean cacheValid;
    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    void processCachedData() {
        rwl.readLock().lock();
        if (!cacheValid) {
            //获取写锁前必须先释放读锁，- 重入时升级不支持：即持有读锁的情况下去获取写锁，会导致获取写锁永久等待
            rwl.readLock().unlock();
            rwl.writeLock().lock();
            try {
                if (!cacheValid) {
                    data = new Object();
                    cacheValid = true;
                }
                //降级为读锁：- 重入时降级支持：即持有写锁的情况下去获取读锁
                rwl.readLock().lock();

            } finally {
                //释放写锁
                rwl.writeLock().unlock();
            }
        }

        try {
            //TODO ...useData ...
        } finally {
            rwl.readLock().unlock();
        }
    }


}




